# encoding:utf-8
from  kivy.app import App

from kivy.uix.boxlayout import BoxLayout
from kivy.properties import ObjectProperty
from kivy.network.urlrequest import UrlRequest

import json

class AddLocationForm(BoxLayout):
    search_input = ObjectProperty()
    # search_results = ObjectProperty()
    def search_location(self):
        search_template = "http://api.openweathermap.org/data/2.5/find?q={}&type=like&mode=json&appid=f06fc0653038791230b56ed5df55444e"
        search_url = search_template.format(self.search_input.text)
        request = UrlRequest(search_url, on_success=self.found_location, debug=True)
        print("The user search for '{}'".format(self.search_input.text))

    def found_location(self, request, data):
        data = json.loads(data.decode()) if not isinstance(data, dict) else data
        cities = ["{} ({})".format(d['name'], d['sys']['country']) for d in data['list']]
        # self.search_results.item_strings = cities
        print ("\n".join(cities))
        self.search_results.adapter.data.clear()
        self.search_results.adapter.data.extend(cities)
        self.search_results._triger_reset_populate()

class WeatherRoot(BoxLayout):
    pass

class WeatherApp(App):
    pass

if __name__ == '__main__':
    WeatherApp().run()
